package com.example.jetpackcomposelearning.compose

import android.net.Uri
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.example.jetpackcomposelearning.R

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun VideoPlayerScreen(videoPath: String, onBackPressed: () -> Unit) {
    val context = LocalContext.current
    val videoUri = remember { Uri.parse(videoPath) }

    var player by remember { mutableStateOf<ExoPlayer?>(null) }
    val playerView = remember { PlayerView(context) }

    DisposableEffect(Unit) {
        player = ExoPlayer.Builder(context).build().apply {
            setMediaItem(MediaItem.fromUri(videoUri))
            prepare()
            playWhenReady = true
        }
        playerView.player = player

        onDispose {
            player?.release()
            playerView.player = null
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        Button(
            onClick = { onBackPressed() },
            modifier = Modifier.align(Alignment.Start).padding(10.dp)
        ) {
            Text("Back")
        }

        Box(modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 50.dp, vertical = 20.dp),
            contentAlignment = Alignment.Center) {
            AndroidView(
                factory = { playerView },
                modifier = Modifier.wrapContentSize(align = Alignment.Center)
            )
        }
    }
}